package com.atmilan.quartz.utils.product;

import com.atmilan.quartz.config.RestTemplateConfig;
import com.atmilan.quartz.model.dto.gb.GbProductResDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class GbProductUtil {

    @Value("${gb.hostName}")
    private String gbHostName;
    @Value("${gb.userName}")
    private String gbUserName;
    @Value("${gb.password}")
    private String gbPassword;

    /**
     * 获取GB商品
     *
     * @return
     */
    public Map<String, GbProductResDTO> getGbProducts() {
        //        List<GbProductResDTO> list = new ArrayList<>();
        Map<String,GbProductResDTO> map = null;
        try {
            Date date = new Date();
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
            log.info("------------------连接ftp:{}服务器----------------------", gbHostName);
            FTPClient ftpClient = new FTPClient();
            //连接ftp
            try {
                ftpClient.connect(gbHostName);
            } catch (IOException e) {
                log.error("----------连接ftp异常:{}---------------", e.getMessage());
            }
            //登陆ftp
            try {
                ftpClient.login(gbUserName, gbPassword);
            } catch (IOException e) {
                log.error("----------登陆ftp异常:{}---------------", e.getMessage());
            }
            map = new HashMap<>();
            //是否连接成功,成功true,失败false
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                log.info("--------------登陆ftp成功-------------------");
                //4.指定要下载的目录, 转移到FTP服务器目录
                try {
                    ftpClient.changeWorkingDirectory("/");
                } catch (IOException e) {
                    log.error("----------转移到FTP服务器目录异常:{}---------------", e.getMessage());
                }
                //5.遍历下载的目录
                ftpClient.enterLocalPassiveMode();
                FTPFile[] ftpFiles = new FTPFile[0];
                try {
                    ftpFiles = ftpClient.listFiles();
                } catch (IOException e) {
                    log.error("----------遍历目录文件列表异常:{}---------------", e.getMessage());
                }
//            log.info("------------当前文件列表:{}------------------", Arrays.toString(ftpFiles));
                int m = 1;
                for (int i = 0; i < ftpFiles.length; i++) {
                    String fn = ftpFiles[i].getName();
//                log.info("---------------遍历第{}个文件,fileName:{}--------------------------------", i + 1, ftpFiles[i].getName());
                    //取当天商品文件
                    if (fn.contains(".csv") && fn.contains(dateStr)) {
                        log.info("----------------解析第{}个文件,fileName:{}----------------------",m, ftpFiles[i].getName());
                        InputStream inputStream = null;
                        try {
                            inputStream = ftpClient.retrieveFileStream(fn);
                        } catch (IOException e) {
                            log.error("----------获取文件{}异常:{}---------------", fn, e.getMessage());
                            e.printStackTrace();
                        }
                        if (inputStream != null) {
                            try {
                                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
//                            File newFile = new File(fn);
//                            //将InputStream转File
//                            FileUtils.copyToFile(inputStream, newFile);
//                            BufferedReader br = new BufferedReader(new FileReader(newFile));
                                String line;
                                String everyLine;
                                br.readLine();
                                // 读取到的内容给line变量
                                while ((line = br.readLine()) != null) {
                                    everyLine = line;
                                    String[] split = everyLine.split("\",\"");
//                                list.add(setParam(GbProductResDTO.class, split));
                                    GbProductResDTO productResDTO = setParam(GbProductResDTO.class, split);
                                    if(null != productResDTO){
                                        map.put(productResDTO.getCodArticolo(),productResDTO);
                                    }
                                }
                                inputStream.close();
                                ftpClient.completePendingCommand();
                            } catch (IOException e) {
                                log.error("----------转换文件{}异常:{}---------------", fn, e.getMessage());
                            } catch (IllegalAccessException e) {
                                log.error("----------对象字段大于数据长度:{}---------------", e.getMessage());
                            } catch (InstantiationException e) {
                                log.error("----------对象实例化异常:{}---------------", e.getMessage());
                            }
                        }
                        m++;

                    }
                }
            } else {
                log.info("--------------连接失败-------------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public <T> T setParam(Class<T> clazz, Object[] args) throws IllegalAccessException, InstantiationException {
        T t = null;
        try {
            if (clazz == null || args == null) {
                throw new IllegalArgumentException();
            }
            t = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            if (fields.length > args.length) {
                log.info("---------gb获取商品数据异常，对象长度：{}；数据长度：{}；数据：{}---------",fields.length,args.length,args);
                return null;
            }
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                fields[i].set(t, removeQuotation(args[i].toString()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 去字符首尾引号
     *
     * @param str
     * @return
     */
    public String removeQuotation(String str) {
        String result = null;
        try {
            result = "";
            if (StringUtils.isBlank(str)) {
                return result;
            }
            char[] begins = str.toCharArray();
            int k = 0;
            int m = begins.length;
            char first = begins[0];
            char last = begins[m - 1];
            if (first == '"') {
                k = 1;
            }
            if (last == '"') {
                m = m - 1;
            }
            result = str.substring(k, m);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String gbHostName= "93.46.41.5";
        String gbUserName = "GEBLAV";
        String gbPassword ="Bj@rlRjg";
        Map<String,GbProductResDTO> map = null;
        try {
            Date date = new Date();
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
            FTPClient ftpClient = new FTPClient();
//            ftpClient.setConnectTimeout(100000000);
//            ftpClient.setDefaultTimeout(100000000);
            ftpClient.setSoTimeout(1000000000);
            //连接ftp
            try {
                ftpClient.connect(gbHostName);
            } catch (IOException e) {
                log.error("----------连接ftp异常:{}---------------", e.getMessage());
            }
            //登陆ftp
            try {
                ftpClient.login(gbUserName, gbPassword);
            } catch (IOException e) {
                log.error("----------登陆ftp异常:{}---------------", e.getMessage());
            }
            map = new HashMap<>();
            //是否连接成功,成功true,失败false
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                log.info("--------------登陆ftp成功-------------------");
                //4.指定要下载的目录, 转移到FTP服务器目录
                try {
                    ftpClient.changeWorkingDirectory("/");
                } catch (IOException e) {
                    log.error("----------转移到FTP服务器目录异常:{}---------------", e.getMessage());
                }
                //5.遍历下载的目录
                ftpClient.enterLocalPassiveMode();
                FTPFile[] ftpFiles = new FTPFile[0];
                try {
                    ftpFiles = ftpClient.listFiles();
                } catch (IOException e) {
                    log.error("----------遍历目录文件列表异常:{}---------------", e.getMessage());
                }
//            log.info("------------当前文件列表:{}------------------", Arrays.toString(ftpFiles));
                int m = 1;
                for (int i = 0; i < ftpFiles.length; i++) {
                    String fn = ftpFiles[i].getName();
//                log.info("---------------遍历第{}个文件,fileName:{}--------------------------------", i + 1, ftpFiles[i].getName());
                    //取当天商品文件
                    if (fn.contains(".csv") && fn.contains(dateStr)) {
                        log.info("----------------解析第{}个文件,fileName:{}----------------------",m, ftpFiles[i].getName());
                        InputStream inputStream = null;
                        try {
                            inputStream = ftpClient.retrieveFileStream(fn);
                        } catch (IOException e) {
                            log.error("----------获取文件{}异常:{}---------------", fn, e.getMessage());
                            e.printStackTrace();
                        }
                        if (inputStream != null) {
                            try {
                                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
//                            File newFile = new File(fn);
//                            //将InputStream转File
//                            FileUtils.copyToFile(inputStream, newFile);
//                            BufferedReader br = new BufferedReader(new FileReader(newFile));
                                String line;
                                String everyLine;
                                br.readLine();
                                // 读取到的内容给line变量
                                while ((line = br.readLine()) != null) {
                                    everyLine = line;
                                    String[] split = everyLine.split("\",\"");
//                                list.add(setParam(GbProductResDTO.class, split));
                                    GbProductResDTO productResDTO = null;
                                    if(null != productResDTO){
                                        map.put(productResDTO.getCodArticolo(),productResDTO);
                                    }
                                }
                                inputStream.close();
                                ftpClient.completePendingCommand();
                            } catch (Exception e) {
                                log.error("----------转换文件{}异常:{}---------------", fn, e.getMessage());
                            }
                        }
                        m++;

                    }
                }
            } else {
                log.info("--------------连接失败-------------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
